import { v4 as uuidv4 } from 'uuid'
const keyPfx = 'decorate'

export function uuid (prefixId = null, category = null) {
  const time = new Date().getTime()
  return `${prefixId}-${category}-${time}-${uuidv4()}`
}

// 自定义临时存储，临时解决针对iframe跨域时无缓存权限的问题
function CustomCache () {}
CustomCache.prototype.setItem = function (key, val) {
  this[key] = val
}
CustomCache.prototype.getItem = function (key) {
  console.log(Object.keys(this))
  return ~Object.keys(this).indexOf(key) ? this[key] : undefined
}
CustomCache.prototype.removeItem = function (key) {
  if (~Object.keys(this).indexOf(key)) {
    delete this[key]
  }
}
CustomCache.prototype.clear = function () {
  Object.keys(this).map(key => delete this[key])
}
// 缓存区分 sessionStorage和localStorage的存储
let localStorage, sessionStorage
try {
  localStorage = window.localStorage
  sessionStorage = window.sessionStorage
} catch (e) {
  console.log('缓存配置失败: ', e)
  localStorage = new CustomCache()
  sessionStorage = new CustomCache()
}
/**
 * 设置缓存
 * @param key {string} 缓存的key
 * @param val {any} 要缓存的值，任意类型
 * @param isLocalStorage {boolean} 是否启用localStorage, 默认不启用
 * @param savedTime {number} 保存的时间，单位·秒 默认无过期时间
 */
export function setCache (key, val, isLocalStorage = false, savedTime = null) {
  const storage = isLocalStorage ? localStorage : sessionStorage
  const tmp = {
    data: val
  }
  if (!key || typeof (key) !== 'string') {
    return false
  }
  if (val === undefined) {
    return null
  }
  key = keyPfx + key
  if (savedTime && !isNaN(savedTime)) {
    tmp.expiredTime = new Date().getTime() + savedTime * 1000
  } else {
    tmp.expiredTime = 0
  }
  try {
    storage.setItem(key, JSON.stringify(tmp))
    return true
  } catch (e) {
    return false
  }
}
// 获取缓存
export function getCache (key, isLocalStorage = false) {
  if (!key && typeof (key) !== 'string') {
    return false
  }
  const storage = isLocalStorage ? localStorage : sessionStorage
  let data
  try {
    data = storage.getItem(keyPfx + key)
  } catch (e) {
    data = ''
  }
  try {
    const tmp = JSON.parse(data)
    if (tmp.expiredTime * 1 === 0 || (tmp.expiredTime * 1 >= new Date().getTime())) {
      return tmp.data
    } else {
      delCache(key)
      return false
    }
  } catch (e) {
    return false
  }
}
// 删除缓存
export function delCache (key, isLocalStorage = false) {
  if (!key) {
    return false
  }
  const storage = isLocalStorage ? localStorage : sessionStorage
  try {
    if (key === '*') {
      storage.clear()
    } else {
      key = keyPfx + key
      storage.removeItem(key)
    }
    return true
  } catch (e) {
    return false
  }
}